<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\CategoryService;
use app\service\GoodsService;
use app\service\HouseInService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Request;

class HouseInController extends BaseController
{
  /**
   * 获取采购订单列表
   */
  public function index(Request $request){
    $page = $request->param('page', 1);
    $pageSize = $request->param('pageSize', env('pager.default.size'));
    $status = $request->param('status', []);
    $houseNumber = $request->param('houseNumber', '');
    $orderField = $request->param('orderField', '');
    $orderSort = $request->param('orderSort', '');
    $data['process'] = $request->param('process', '');
    if ($data['process'] === '') {
      return $this->send400Response('process必填');
    }
    $conditions = [];
    if(strlen($data['process']) > 0){
      $conditions[] = ['process',$data['process'],'='];
    }
    if ($status) {
      $conditions[] = ['status', $status, 'IN'];
    }
    if ($houseNumber) {
      $conditions[] = ['house_in_number', '%'.$houseNumber.'%', 'like'];
    }
    $list = HouseInService::getInstance()->getHouseInByCondition($conditions, '*', $orderField, $orderSort);
    // 分页
    $count = count($list); //总条数
    $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
    $pager = [
      'totalCount' => $count,
      'pageSize' => intval($pageSize),
      'currPage' => intval($page),
      'totalPage' => intval($count/$pageSize)+1
    ];
    $data = array_slice($list, $start, intval($pageSize));
    return $this->send200ResponseWithPager($data,$pager);
  }

  /**
   * 根据采购单号获取采购订单明细
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function read($id) {
    $result = HouseInService::getModel()
      ->find($id)
      ->toArray();
    $conditions = [['h.status', 1, '='], ['o.id', $id, '='], ['o.status', 0,'<>']];
    $detail = HouseInService::getInstance()->getHouseInJoinGoods($conditions);
    $result['productList'] = $detail;
    return $this->send200Response($result);
  }

  /**
   * 采购单修改
   */
  public function update(Request $request, $id) {
    $data = $request->param('data', []);
    $supplier = $request->param('supplier', '');
    $default_time = $request->param('default_time', '');
    if (!$data) {
      return $this->send400Response('data必填');
    }
    if (!$supplier) {
      return ['status' => false, 'msg' => '供应商必填'];
    }
    if (!$default_time) {
      return ['status' => false, 'msg' => '预计入库时间必填'];
    }
    $default_time = date('Y-m-d', strtotime($default_time));
    $result = HouseInService::getInstance()->updateHouseInOrder($id, $supplier, $default_time, $data);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 获取入库订单明细列表
   */
  public function detailList(Request $request) {
    // 获取
    $page = $request->param('page', 1);
    $pageSize = $request->param('pageSize', env('pager.default.size'));
    $status = $request->param('status', '');
    $process = $request->param('process', '');
    if ($process === '') {
      return $this->send400Response('process必填');
    }
    $conditions = [];
    if(strlen($process) > 0){
      $conditions[] = ['o.process',$process,'='];
    }
    if (strlen($status) > 0) {
      $conditions[] = ['o.status', $status, '='];
    }
    $conditions[] = ['h.status', 1, '='];
    $conditions[] = ['o.status', 0,'<>'];
    $order = ['o.default_time' => 'DESC', 'o.house_in_number' => 'DESC', 'h.id' => 'DESC'];
    $list = HouseInService::getInstance()->getHouseInJoinGoods($conditions, $order);
    // 分页
    $count = count($list); //总条数
    $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
    $pager = [
      'totalCount' => $count,
      'pageSize' => intval($pageSize),
      'currPage' => intval($page),
      'totalPage' => intval($count/$pageSize)+1
    ];
    $data = array_slice($list, $start, intval($pageSize));
    return $this->send200ResponseWithPager($data,$pager);
  }

  /**
   * 入库单条信息删除
   */
  public function deleteDetail($id){
    $result = HouseInService::getInstance()->deleteHouseIn($id);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 审核采购单
   */
  public function check(Request $request) {
    $check = $request->param('check', '');
    $orderId = $request->param('orderId', '');
    $comment = $request->param('comment', '');
    if ($check === '') {
      return $this->send400Response('check必填');
    }
    if ($orderId === '') {
      return $this->send400Response('orderId必填');
    }
    $result = HouseInService::getInstance()->checkHouseInOrder($orderId, $check, $comment);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 删除原料审批采购单
   */
  public function delete($id) {
    $result = HouseInService::getInstance()->deleteHouseInOrder($id);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 导出至excel
   */
  public function export(Request $request) {
    $status = $request->param('status', '');
    $process = $request->param('process', '');
    $groupid = $request->param('groupid', 1);
    if ($process === '') {
      return $this->send400Response('process必填');
    }
    $conditions = [];
    $conditions[] = ['o.process',$process,'='];
    $conditions[] = ['h.status',1,'='];
    $conditions[] = ['o.status', 0,'<>'];
    if ($status !== '') {
      $conditions[] = ['o.status', $status, '='];
    }
    $list = HouseInService::getInstance()->getHouseInJoinGoods($conditions);
    // 获取分类
    $category = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
    $category = array_column($category, 'category_name', 'id');
    foreach ($list as &$value) {
      $value['category'] = isset($category[$value['category_id']]) ? $category[$value['category_id']] : '';
    }
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    if ($groupid) {
      $sheet->getColumnDimension('A')->setWidth(20);
      $sheet->getColumnDimension('B')->setWidth(15);
      $sheet->getColumnDimension('C')->setWidth(15);
      $sheet->getColumnDimension('D')->setWidth(20);
      $sheet->getColumnDimension('E')->setWidth(15);
      $sheet->getColumnDimension('F')->setWidth(15);
      $sheet->getColumnDimension('G')->setWidth(15);
      $sheet->getColumnDimension('H')->setWidth(15);
      $sheet->getColumnDimension('I')->setWidth(15);
      $sheet->getColumnDimension('J')->setWidth(20);
      if (!$process) {
        $sheet->getColumnDimension('K')->setWidth(20);
      }
      $sheet->setCellValue('A1', $process ? '生产单号' : '采购单号');
      $sheet->setCellValue('B1', '日期');
      $sheet->setCellValue('C1', '分类');
      $sheet->setCellValue('D1', '商品名称');
      $sheet->setCellValue('E1', $process ? '生产数量' : '采购数量');
      $sheet->setCellValue('F1', $process ? '生产单位' : '采购单位');
      $sheet->setCellValue('G1', '入库数量');
      $sheet->setCellValue('H1', '入库单位');
      $sheet->setCellValue('I1', '转换比例');
      $sheet->setCellValue('J1', '备注');
      if (!$process) {
        $sheet->setCellValue('K1', '供应商');
      }
      $row = 1;
      foreach($list as $v){
        $row++;
        $sheet->setCellValue("A{$row}", " ".$v['house_in_number']);
        $sheet->setCellValue("B{$row}", date('Y-m-d', strtotime($v['default_time'])));
        $sheet->setCellValue("C{$row}", $v['category']);
        $sheet->setCellValue("D{$row}", $v['name']);
        $sheet->setCellValue("E{$row}", $v['count_in']);
        $sheet->setCellValue("F{$row}", $v['unit_in']);
        $sheet->setCellValue("G{$row}", $v['count']);
        $sheet->setCellValue("H{$row}", $v['unit']);
        $sheet->setCellValue("I{$row}", $v['conversion']);
        $sheet->setCellValue("J{$row}", $v['comment']);
        if (!$process) {
          $sheet->setCellValue("K{$row}", $v['supplier']);
        }
      }
    } else {
      $sheet->getColumnDimension('A')->setWidth(20);
      $sheet->getColumnDimension('B')->setWidth(15);
      $sheet->getColumnDimension('C')->setWidth(15);
      $sheet->getColumnDimension('D')->setWidth(20);
      $sheet->getColumnDimension('E')->setWidth(15);
      $sheet->getColumnDimension('F')->setWidth(15);
      $sheet->getColumnDimension('G')->setWidth(15);
      $sheet->getColumnDimension('H')->setWidth(15);
      $sheet->getColumnDimension('I')->setWidth(15);
      $sheet->getColumnDimension('J')->setWidth(15);
      $sheet->getColumnDimension('K')->setWidth(15);
      $sheet->getColumnDimension('L')->setWidth(15);
      $sheet->getColumnDimension('M')->setWidth(20);
      if (!$process) {
        $sheet->getColumnDimension('N')->setWidth(20);
      }
      $sheet->setCellValue('A1', $process ? '生产单号' : '采购单号');
      $sheet->setCellValue('B1', '日期');
      $sheet->setCellValue('C1', '分类');
      $sheet->setCellValue('D1', '商品名称');
      $sheet->setCellValue('E1', $process ? '生产数量' : '采购数量');
      $sheet->setCellValue('F1', $process ? '生产单位' : '采购单位');
      $sheet->setCellValue('G1', $process ? '生产成本' : '采购成本');
      $sheet->setCellValue('H1', '入库数量');
      $sheet->setCellValue('I1', '入库单位');
      $sheet->setCellValue('J1', '入库成本');
      $sheet->setCellValue('K1', '转换比例');
      $sheet->setCellValue('L1', '总成本');
      $sheet->setCellValue('M1', '备注');
      if (!$process) {
        $sheet->setCellValue('N1', '供应商');
      }
      $row = 1;
      foreach($list as $v){
        $row++;
        $sheet->setCellValue("A{$row}", " ".$v['house_in_number']);
        $sheet->setCellValue("B{$row}", date('Y-m-d', strtotime($v['default_time'])));
        $sheet->setCellValue("C{$row}", $v['category']);
        $sheet->setCellValue("D{$row}", $v['name']);
        $sheet->setCellValue("E{$row}", $v['count_in']);
        $sheet->setCellValue("F{$row}", $v['unit_in']);
        $sheet->setCellValue("G{$row}", $v['price_in']);
        $sheet->setCellValue("H{$row}", $v['count']);
        $sheet->setCellValue("I{$row}", $v['unit']);
        $sheet->setCellValue("J{$row}", $v['price']);
        $sheet->setCellValue("K{$row}", $v['conversion']);
        $sheet->setCellValue("L{$row}", $v['total_amount']);
        $sheet->setCellValue("M{$row}", $v['comment']);
        if (!$process) {
          $sheet->setCellValue("N{$row}", $v['supplier']);
        }
      }
    }
    header("Content-type: application/octet-stream;charset=utf-8");
    header('Content-Disposition: attachment;filename="采购明细导出.xlsx"');
    header('Cache-Control: max-age=0');
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
  }
}
